<template>
  <main-content
    :title="mode === 'edit' ? '编辑优惠券' : '新增优惠券'"
    back
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="formRules"
      :label-width="120"
    >
      <el-form-item
        label="优惠券名称"
        prop="couponName"
        class="common-form-item"
      >
        <el-input
          v-model="form.couponName"
          :max="20"
          show-word-limit
          placeholder="请输入优惠券名称"
          @blur="form.couponName = form?.couponName.trim()"
        />
      </el-form-item>

      <el-form-item
        label="优惠券类型"
        prop="couponType"
      >
        <div
          class="radio-box"
          :class="{'radio-box__disabled': mode === 'edit'}"
        >
          <div
            v-for="item in CouponType"
            :key="item.value"
            class="radio-item"
            @click="handleCouponTypeChange(item.value)"
          >
            <div class="coupon-type-inner">
              <div class="title1">
                {{ item.label }}
              </div>
              <div class="title2">
                {{ item.desc }}
              </div>
            </div>

            <div
              v-show="item.value === form.couponType"
              class="radio-item-checked-cover"
            >
              <el-icon class="check-icon">
                <Check />
              </el-icon>
            </div>
          </div>
        </div>
      </el-form-item>

      <el-form-item
        label="优惠规则"
        class="common-form-item"
        prop="discountRule"
      >
        <div
          v-if="form.couponType === 1"
          class="discount-rule"
        >
          <span>消费满</span>
          <el-input
            v-model="form.fullPrice"
            class="inline-form-input form-input__120"
            @blur="form.fullPrice = form?.fullPrice?.trim()"
          />
          <span>元，立减</span>
          <el-input
            v-model="form.reducePrice"
            class="inline-form-input form-input__120"
            @blur="form.reducePrice = form?.reducePrice?.trim()"
          />
          <span>元</span>
        </div>
        <div
          v-if="form.couponType === 2"
          class="discount-rule"
        >
          <span>消费满</span>
          <el-input
            v-model="form.fullPrice"
            class="inline-form-input form-input__120"
            @blur="form.fullPrice = form?.fullPrice?.trim()"
          />
          <span>元，可享受折扣</span>
          <el-input
            v-model="form.discount"
            class="inline-form-input form-input__120"
            @blur="form.discount = form?.discount?.trim()"
          />
          <span>（折扣比例:原价为1，0.99即为九九折）</span>
          <el-input
            v-model="form.maxDiscountPrice"
            class="inline-form-input form-input__120"
            @blur="form.maxDiscountPrice = form?.maxDiscountPrice?.trim()"
          />
          <span>元封顶</span>
        </div>
        <div
          v-if="form.couponType === 3"
          class="discount-rule"
        >
          使用范围商品任选一件兑换
        </div>
      </el-form-item>

      <el-form-item
        label="使用范围"
        prop="useRange"
      >
        <el-radio-group
          v-model="form.useRange"
          @change="handleUseRangeChange"
        >
          <el-radio
            v-for="item in UseRangeList"
            :key="item.value"
            :label="item.value"
          >
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item
        v-if="form.useRange === 1"
        label="选择活动"
        prop="businessData"
      >
        <sc-selector
          v-model="form.businessId"
          placeholder="请选择活动"
          type="activity"
          :params="{}"
        >
          <template #expand-pop="props">
            <div>
              开始时间：{{ props.data?.info?.startTime }} <br>
              结束时间：{{ props.data?.info?.endTime }}
            </div>
          </template>
        </sc-selector>
      </el-form-item>

      <el-form-item
        v-if="form.useRange === 2 || form.useRange === 3 || form.useRange === 4"
        label="选择商城"
        prop="businessData"
        class="business-form-item business-form-item__column"
      >
        <div class="business-row">
          <!-- 商城 -->
          <el-select
            v-model="form.businessId"
            placeholder="请选择商城"
            class="business-column-item"
            @change="getBusinessDataById"
          >
            <el-option
              v-for="item in mallList"
              :key="item.id"
              :label="item.mallName"
              :value="item.id"
            />
          </el-select>

          <!-- 商城商品 -->
          <div
            v-if="form.useRange === 3 && form.businessId"
            class="business-column-item goods-select"
            @click="showGoodsSelect"
          >
            <el-icon> <Plus /> </el-icon>
            <div>添加商品</div>
          </div>

          <!-- 商城商品分类 -->
          <el-select
            v-if="form.useRange === 4 && form.businessId"
            v-model="chooseCategoryList"
            placeholder="请选择商城商品分类"
            class="business-column-item cate-select"
            multiple
            filterable
          >
            <el-option
              v-for="item in mallGoodsCategoryList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </div>

        <div class="business-row">
          <Gallery
            :list="chooseGoodsList"
            src-key="thumbnailUrl"
            alt-key="name"
            :width="100"
            :height="100"
            @close="deleteChooseGoods"
          />
        </div>
      </el-form-item>

      <el-form-item
        label="领取时间"
        class="common-form-item"
        prop="receiveTime"
      >
        <el-date-picker
          v-model="receiveTimeModel"
          type="daterange"
          range-separator="To"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :disabled-date="getDisabledDate"
          @visible-change="formRef?.validateField('receiveTime')"
        />
      </el-form-item>

      <el-form-item
        label="领取时间限制"
        prop="receiveType"
        class="receive-type-radio-group"
      >
        <el-radio-group
          v-model="form.receiveType"
          class="column-radio-group"
          @change="handleReceiveTypeChange"
        >
          <el-radio :label="0">
            领取时间内，均可领取
          </el-radio>
          <el-radio :label="1">
            <span class="radio-inner-item">领取时间内，每天</span>
            <el-time-picker
              v-model="receiveLimitDayTimeModel"
              class="radio-inner-item"
              is-range
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
            />
            <span class="radio-inner-item">可领取</span>
          </el-radio>
          <el-radio
            :label="2"
            class="radio-item__align-center"
          >
            <span class="radio-inner-item">领取时间内，每周</span>
            <el-select
              v-model="receiveWeekDayModel"
              multiple
              class="radio-inner-item select-width__120"
            >
              <el-option
                v-for="item in weekDays"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <el-time-picker
              v-model="receiveLimitWeekTimeModel"
              class="radio-inner-item"
              is-range
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
            />
            <span class="radio-inner-item">可领取</span>
          </el-radio>
          <el-radio :label="3">
            <span class="radio-inner-item">领取时间内，每月</span>     
            <el-select
              v-model="receiveMonthModel"
              multiple
              class="radio-inner-item  select-width__120"
            >
              <el-option
                v-for="(item) in monthDays"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
            <el-time-picker
              v-model="receiveLimitMonthTimeModel"
              class="radio-inner-item"
              is-range
              range-separator="-"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
            />
            <span class="radio-inner-item">可领取</span>
          </el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item
        label="使用开始时间"
        prop="takeEffectType"
      >
        <el-radio-group
          v-model="form.takeEffectType"
          class="column-radio-group"
        >
          <el-radio
            v-for="item in takeEffectTypes"
            :key="item.value"
            :label="item.value"
          >
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item
        label="使用结束时间"
        prop="useType"
      >
        <el-radio-group
          v-model="form.useType"
          class="column-radio-group"
          @change="handleUseTypeChange"
        >
          <el-radio :label="0">
            <span class="radio-inner-item">
              固定时间
            </span>
            
            <el-date-picker
              v-model="useFixEndTimeModel"
              type="datetime"
              placeholder="请选择固定时间范围"
              class="radio-inner-item"
            />

            <span class="radio-inner-item">
              时间内均可使用
            </span>
          </el-radio>

          <el-radio
            :label="1"
          >
            <div class="endtime-radio-item">
              <div>
                <span class="radio-inner-item">相对开始时间</span>
                <el-input
                  v-model="form.useDayNum"
                  class="radio-inner-item input-width__120"
                />
                <span class="radio-inner-item">天内可使用</span>
              </div>
              <div>
                <el-icon><InfoFilled /></el-icon>
                1 表示当天失效
              </div>
            </div>
          </el-radio>

          <el-radio :label="2">
            <div class="endtime-radio-item">
              <div>
                <span class="radio-inner-item">相对开始时间</span>
                <el-input
                  v-model="form.useMonthNum"
                  class="radio-inner-item input-width__120"
                />
                <span class="radio-inner-item">月内可使用</span>
              </div>
              <div>
                <el-icon><InfoFilled /></el-icon>
                1 表示当月月底失效,2表示次月月底失效,依此类推
              </div>
            </div>
          </el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item
        label="优惠券数量预警"
        prop="couponWarning"
        class="common-form-item"
      >
        <el-switch
          v-model="form.couponWarningStatus"
          class="gapped-form-item"
          :active-value="1"
          :inactive-value="0"
          @change="handleCouponWarningStatusChange"
        />
        <span class="gapped-form-item">预警阈值</span>
        <el-input
          v-model="form.warningNum"
          class="gapped-form-item form-input__120"
          @blur="formRef?.validateField('couponWarning');form.warningNum = form.warningNum?.trim()"
        />
      </el-form-item>

      <div class="coupon-warning-notice">
        请在优惠券管理配置预警通知,否则无法触达相关人员
      </div>

      <el-form-item
        label="优惠券使用说明"
        prop="couponUseDetail"
      >
        <el-input
          v-model="form.couponUseDetail"
          :rows="5"
          type="textarea"
          placeholder="请输入优惠券使用说明"
        />
      </el-form-item>
    </el-form>

    <template #fixed-bottom>
      <div class="fixed-bottom">
        <el-button
          type="primary"
          @click="submit"
        >
          提交
        </el-button>
      </div>
    </template>
  </main-content>

  <goods-select-2
    v-model:show="isShowGoodsSelect"
    :values="chooseGoodsList"
    multi-select
    :search-form="selectGoodsSearchForm"
    @confirm="handleGoodsSelectConfirm"
  />
</template>

<script setup lang="ts">
import type { Ref, WritableComputedRef } from "vue";
import type { FormRules } from "element-plus";
import type { InternalRuleItem } from 'async-validator';
import type { IEditCouponData } from "@/api/modules/marketingTool";
import type { IMallPageItem, IGoodsCateItem } from "@/api/modules/pointsMall";
import moment from "moment";
import { ElMessage, ElMessageBox } from "element-plus"
import { Check } from "@element-plus/icons-vue"
import { useCouponType } from "@/views/marketingTool/compositions/useCouponType"
import { useCouponUseRange } from "@/views/marketingTool/compositions/useCouponUseRange"
import { getMallList, getGoodsCategory } from "@/api/pointsMall";
import { getPage2 } from "@/api/actapp";
import { saveOrUpdateCouponDefine, getOneCouponDefine } from "@/api/marketingTool"
import GoodsSelect2 from "@/components/goodsCenter/GoodsSelect2.vue";
import { positiveNumber_decimal$2, positiveInteger } from "@/utils/commonRegexp";
import { toChineseNumber } from "@/utils";
import { useTakeEffectType } from "@/views/marketingTool/compositions/useTakeEffectType"


const router = useRouter();
const route = useRoute();
const { CouponType } = useCouponType()
const { TakeEffectTypes } = useTakeEffectType()
const { UseRangeList } = useCouponUseRange()

const weekDays = ref(Array.from({
  length: 7 
}, (_, index) => ({ 
  value: '' + index + 1, 
  label: index + 1 === 7 ? '日' : toChineseNumber(index + 1)
})))

const monthDays = ref([])
for (let i = 1; i <= 31; i++) {
  monthDays.value.push(i)
}

const takeEffectTypes = ref(TakeEffectTypes)

const mode = computed(() => {
  let _mode = ''
  if (route.path.includes('edit') || route.path.includes("copy")) {
    _mode = "edit"
  } else {
    _mode = "create"
  }

  return _mode
})

const action_copy = computed(() => route.query.action === 'copy')

const isEmpty = (value: undefined | null | string | number) => value === undefined || value === null || value === ''

const formRef = ref();
const formRules: Ref<FormRules> = ref({
  couponName: [ {
    message: "请输入优惠券名称",
    trigger: "blur",
    required: true,
  } ],
  couponType: [ {
    message: "请选择优惠券类型",
    required: true,
  } ],
  discountRule: [ {
    required: true,
    validator(rule: InternalRuleItem, value: number, callback: (e?: Error | string) => void) {
      if (form.value.couponType === 1) {
        if (isEmpty(form.value.fullPrice)) {
          callback("请填写消费满XX元")
          return
        }

        if (!positiveNumber_decimal$2.test('' + form.value.fullPrice)) {
          callback("消费满XX元，需填写数字，且保留2位小数")
          return
        }

        if (isEmpty(form.value.reducePrice)) {
          callback("请填写立减XX元")
          return
        }

        if (!positiveNumber_decimal$2.test('' + form.value.reducePrice)) {
          callback("立减XX元，需填写数字，且保留2位小数")
          return
        }

        if (Number(form.value.reducePrice) > Number(form.value.fullPrice)) {
          callback("立减XX元不能大于消费满XX元")
        }
      }

      if (form.value.couponType === 2) {
        if ( isEmpty(form.value.fullPrice)) {
          callback("请填写消费满XX元")
          return
        }

        if (!positiveNumber_decimal$2.test('' + form.value.fullPrice)) {
          callback("消费满XX元，需填写数字，且保留2位小数")
          return
        }

        if (isEmpty(form.value.discount)) {
          callback("请填写可享受折扣XX")
          return
        }

        if (!positiveNumber_decimal$2.test('' + form.value.discount)) {
          callback("可享受折扣XX，需填写数字，且保留2位小数")
          return
        }

        if (Number(form.value.discount) <= 0 || Number(form.value.discount) >= 1) {
          callback("可享受折扣XX，需大于0，小于1")
          return
        }

        if (isEmpty(form.value.maxDiscountPrice)) {
          callback("请填写XX元封顶")
          return
        }

        if (!positiveNumber_decimal$2.test('' + form.value.maxDiscountPrice)) {
          callback("XX元封顶，需填写数字，且保留2位小数")
          return
        }
      }

      callback()
    },
    trigger: 'blur',
  } ],
  useRange: [ {
    required: true,
    message: "请选择使用范围",
    trigger: "blur",
  } ],
  businessData: [ {
    required: true,
    validator(rule: InternalRuleItem, value: number, callback: (e?: Error | string) => void) {
      if (form.value.useRange === 1) {
        if (!form.value.businessId) {
          callback("请选择活动")
          return
        }
      }

      if (form.value.useRange === 2) {
        if (!form.value.businessId) {
          callback("请选择商城")
          return
        }
      }

      if (form.value.useRange === 3) {
        if (!form.value.businessId) {
          callback("请选择商城")
          return
        }

        if (!form.value.businessGoodsIds) {
          callback("请选择商品")
          return
        }
      }

      if (form.value.useRange === 4) {
        if (!form.value.businessId) {
          callback("请选择商城")
          return
        }

        if (!form.value.businessCategoryIds) {
          callback("请选择商品分类")
          return
        }
      }

      callback()
    },
    trigger: [ 'blur', 'change' ]
  } ],
  receiveTime: [ {
    required: true,
    validator(rule: InternalRuleItem, value: number, callback: (e?: Error | string) => void) {
      if (!form.value.receiveStartTime || !form.value.receiveEndTime) {
        callback("请选择领取时间")
        return 
      }
      callback();
    },
  } ],
  receiveType: [ {
    required: true,
    validator(rule: InternalRuleItem, value: number, callback: (e?: Error | string) => void) {
      if (form.value.receiveType === 1) {
        if (!form.value.receiveRangeStartTime || !form.value.receiveRangeEndTime) {
          callback("请设置领取限制时间范围")
          return
        }
      }

      if (form.value.receiveType === 2) {
        if (!form.value.receiveWeekDay) {
          callback("请选择时间限制，每周XX")
          return
        }

        if (!form.value.receiveRangeStartTime || !form.value.receiveRangeEndTime) {
          callback("请设置领取限制时间范围")
          return
        }
      }

      if (form.value.receiveType === 3 ) {
        if (!form.value.receiveMonth) {
          callback("请选择时间限制，每月XX")
          return
        }

        if (!form.value.receiveRangeStartTime || !form.value.receiveRangeEndTime) {
          callback("请设置领取限制时间范围")
          return
        }
      }

      callback()
    }
  } ],
  takeEffectType: [ {
    required: true,
    message: "请选择使用开始时间",
    trigger: "change",
  } ],
  useType: [ {
    required: true,
    validator(rule: InternalRuleItem, value: number, callback: (e?: Error | string) => void) {
      // 固定时间
      if (form.value.useType === 0) {
        if (!form.value.useFixEndTime) {
          callback("请输入固定时间范围")
          return
        }
      }

      if (form.value.useType === 1) {
        if (!form.value.useDayNum) {
          callback("请输入相对开始时间（天）")
          return
        }

        if (!positiveInteger.test("" + form.value.useDayNum)) {
          callback("相对开始时间（天）需为数字且大于0")
          return
        } 
      }

      if (form.value.useType === 2) {
        if (!form.value.useMonthNum) {
          callback("请输入相对开始时间（月）")
          return
        }

        if (!positiveInteger.test("" + form.value.useMonthNum)) {
          callback("相对开始时间（月）需为数字且大于0")
          return
        } 
      }

      callback()
    }
  } ],
  couponWarning: [ {
    required: false,
    validator(rule: InternalRuleItem, value: number, callback: (e?: Error | string) => void) {
      if (form.value.couponWarningStatus) {
        if (!positiveInteger.test("" + form.value.warningNum)) {
          callback("请输入优惠券数量预警阈值，需大于0的整数")
          return
        }
      }

      callback()
    },
  } ],
  couponUseDetail: [ {
    required: true,
    message: "请输入优惠券使用说明",
    trigger: "blur"
  } ]
})
const form:Ref<IEditCouponData> = ref({
  id: undefined,
  couponName: "",
  // 优惠券类型
  couponType: 1,
  // 优惠券规则
  fullPrice: undefined,
  reducePrice: undefined,
  discount: undefined,
  discountRule: "",
  maxDiscountPrice: undefined,
  // 使用范围
  useRange: 1,
  businessId: undefined,
  businessGoodsIds: undefined,
  businessCategoryIds: undefined,
  // 领取时间
  receiveStartTime: undefined,
  receiveEndTime: undefined,
  receiveWeekDay: undefined,
  receiveMonth: undefined,
  receiveRangeStartTime: undefined,
  receiveRangeEndTime: undefined,
  // 领取时间限制
  receiveType: 0,
  // 使用开始时间
  takeEffectType: 0,
  // 使用结束时间
  useType: 0,
  useFixEndTime: undefined,
  useDayNum: undefined,
  useMonthNum: undefined,
  couponWarningStatus: 0,
  warningNum: undefined,
  couponUseDetail: "",
})

// 优惠券类型
const handleCouponTypeChange = (value: number) => {
  if (form.value.status === 0) {
    // 已启用
    ElMessage.warning("当前优惠券已启用，不可修改优惠券类型")
    return
  }
  form.value.couponType = value;
  form.value.fullPrice = undefined;
  form.value.reducePrice = undefined;
  form.value.discount = undefined;
  form.value.maxDiscountPrice = undefined;

  formRef.value.clearValidate("discountRule")
}

// 选择商城商品
const isShowGoodsSelect = ref(false);
const selectGoodsSearchForm = ref({
  mallId: -1,
})
const chooseGoodsList: Ref<{ id: number }[]> = ref([]);
const showGoodsSelect = () => {
  if (form.value.useRange === 3 && !form.value.businessId) {
    ElMessage.warning("请先选择商城")
    return
  }
  selectGoodsSearchForm.value.mallId = form.value.businessId ?? -1;
  isShowGoodsSelect.value = true
}
const handleGoodsSelectConfirm = (selected: {id: number}[]) => {
  // console.log("goods selected", selected)
  chooseGoodsList.value = selected;
  form.value.businessGoodsIds = selected.map(item => item.id).join(",");
  formRef.value.validateField('businessData', (valid: boolean) => {
    if (!valid) {
      // formRef.value.scrollToField('businessData')
    }
  })
}
// 删
const deleteChooseGoods = ({ index }: { index: number }) => {
  ElMessageBox.confirm("确定删除？", "提示", {
  }).then(() => {
    chooseGoodsList.value.splice(index, 1);
    form.value.businessGoodsIds = chooseGoodsList.value.map(item => item.id).join(",");
    formRef.value.validateField('businessData', (valid: boolean) => {
      if (!valid) {
        // formRef.value.scrollToField('businessData')
      }
    })
  }).catch(() => {
    // cancel
  })
}

const chooseCategoryList = ref([])
watch(chooseCategoryList, (value) => {
  form.value.businessCategoryIds = value.join(",")
})

// 商城列表
const mallList:Ref<IMallPageItem[]> = ref([])
const _getMallList = async () => {
  const rs = await getMallList()

  if (rs.code === 200) {
    mallList.value = rs?.payload ?? []
  }
}

// 商城商品分类
const mallGoodsCategoryList:Ref<IGoodsCateItem[]> = ref([])
const _getMallGoodsCategoryList = async () => {
  if (!form.value.businessId) {
    return
  }

  const rs = await getGoodsCategory({ id: form.value.businessId })
  if (rs.code == 200) {
    mallGoodsCategoryList.value = rs?.payload ?? []
  }
}

// 商城商品
const _getMallGoods = async () => {
  if (!form.value.businessId) {
    return
  }

  const rs = await getPage2({
    mallId: form.value.businessId,
    goodsIds: form.value.businessGoodsIds?.split(",") ?? [],
    currentPage: 1,
    showCount: -1,
  });

  if (rs.code === 200) {
    chooseGoodsList.value = rs.payload ?? [];
  }
}

const getBusinessDataById = () => {
  if (form.value.useRange === 4) {
    _getMallGoodsCategoryList()
  }

  form.value.businessCategoryIds = undefined;
  form.value.businessGoodsIds = undefined;
  chooseGoodsList.value = []
  chooseCategoryList.value = []
}

const handleUseRangeChange = () => {
  form.value.businessId = undefined;
  form.value.businessCategoryIds = undefined;
  form.value.businessGoodsIds = undefined;
  chooseGoodsList.value = []
  chooseCategoryList.value = []
}

// 领取时间
const receiveTimeModel:WritableComputedRef<(number | undefined)[]> = computed({
  get() {
    return [ form.value.receiveStartTime, form.value.receiveEndTime ]
  },
  set(value) {
    console.log("receiveTimeModel value", value)
    if (!value) {
      receiveTimeModel.value = []
      return
    }
    form.value.receiveStartTime = value[0] ? moment(value[0]).startOf('day').valueOf() : value[0]
    form.value.receiveEndTime = value[1] ? moment(value[1]).endOf('day').valueOf() : value[1]
  }
})

const receiveWeekDayModel:Ref<string[]> = ref([]); // 领取时间日期类型 每周
const receiveMonthModel:Ref<string[]> = ref([]); // 领取时间日期类型 每月
watch(receiveWeekDayModel, (val) => {
  // console.log("receiveWeekDayModel val", val)
  form.value.receiveWeekDay = val instanceof Array ? val.join(",") : val;
})
watch(receiveMonthModel, (val) => {
  // console.log("receiveMonthModel val", val)
  form.value.receiveMonth = val instanceof Array ? val.join(",") : val
})

// 领取时间类型下，时间model
const receiveLimitDayTimeModel:Ref<number[]> = ref([])
const receiveLimitWeekTimeModel:Ref<number[]> = ref([])
const receiveLimitMonthTimeModel:Ref<number[]> = ref([])
watch(receiveLimitDayTimeModel, (val) => {
  // console.log("day val", val[0], val[1])
  form.value.receiveRangeStartTime = val[0] ? moment(val[0]).format("HH:mm:ss") : undefined;
  form.value.receiveRangeEndTime = val[1] ? moment(val[1]).format("HH:mm:ss") : undefined;
})
watch(receiveLimitWeekTimeModel, (val) => {
  // console.log("week val", val)
  form.value.receiveRangeStartTime = val[0] ? moment(val[0]).format("HH:mm:ss") : undefined;
  form.value.receiveRangeEndTime = val[1] ? moment(val[1]).format("HH:mm:ss") : undefined;
})
watch(receiveLimitMonthTimeModel, (val) => {
  // console.log("month val", val)
  form.value.receiveRangeStartTime = val[0] ? moment(val[0]).format("HH:mm:ss") : undefined;
  form.value.receiveRangeEndTime = val[1] ? moment(val[1]).format("HH:mm:ss") : undefined;
})

// 领取时间限制
const handleReceiveTypeChange = () => {
  receiveLimitDayTimeModel.value = []
  receiveLimitWeekTimeModel.value = []
  receiveLimitMonthTimeModel.value = []
  form.value.receiveWeekDay = undefined
  form.value.receiveMonth = undefined
  // form.value.receiveType = value
  nextTick(() => {
    formRef.value.clearValidate("receiveType")
  })
}

// 使用结束时间
const handleUseTypeChange = () => {
  form.value.useFixEndTime = undefined;
  form.value.useDayNum = undefined;
  form.value.useMonthNum = undefined;
  nextTick(() => {
    formRef.value.clearValidate("useType")
  })
}

const useFixEndTimeModel = computed({
  get() {
    return form.value.useFixEndTime
  },
  set(newValue) {
    form.value.useFixEndTime = moment(newValue).valueOf()
  }
})

// 优惠券数量预警
const handleCouponWarningStatusChange = () => {
  formRef.value?.validateField('couponWarning');
  form.value.warningNum = undefined;
}

// 今天之前禁用日期
const getDisabledDate = (date: Date) => {
  return moment(date).valueOf() < moment().startOf('day').valueOf()
}

// 根据HH:mm:ss 格式的字符串获取对应的时间戳
const getTimestampByHHmmss = (HHmmssString: string) => {
  if (!HHmmssString) {
    return moment().valueOf()
  }
    
  const [ hour, minute, second ] = HHmmssString.split(":")
  // 数据仅需时分秒，默认日期到今天
  return moment().hour(hour).minute(minute).second(second).valueOf()
}

const submit = () => {
  // console.log("form => ", form.value)
  formRef.value?.validate(async (valid: boolean) => {
    // console.log("valid", valid)
    if (valid) {
      form.value.discountRule = JSON.stringify({ 
        fullPrice: form.value.fullPrice, 
        reducePrice: form.value.reducePrice, 
        maxDiscountPrice: form.value.maxDiscountPrice,
        discount: form.value.discount
      })
      if (action_copy.value) {
        form.value.id = undefined
      }

      const rs = await saveOrUpdateCouponDefine(form.value)
      if (rs.code === 200) {
        ElMessage.success("已提交")
        router.back();
      }
    } else {
      ElMessage.error("校验未通过，请检查表单")
    }
  })
}

const _getOneCouponDefine = async () => {
  const rs = await getOneCouponDefine({
    id: <string>route.query.id
  })

  if (rs.code === 200 && rs.payload) {
    form.value = rs.payload
  }
}

// 回显表单
const echoForm = async () => {
  console.log("回显表单！！！")
  await _getOneCouponDefine()

  // 使用范围 商城商品
  if (form.value.useRange === 3) {
    chooseGoodsList.value = (form.value.businessGoodsIds?.split(",") ?? []).map(i => ({ id: Number(i) }))
    _getMallGoods()
  }

  if (form.value.useRange === 4) {
    chooseCategoryList.value = (form.value.businessCategoryIds?.split(",") ?? []).map(i => Number(i))
    _getMallGoodsCategoryList()
  }

  // 优惠规则
  if (form.value.discountRule) {
    const _parsedDiscountRule = JSON.parse(form.value.discountRule)
    form.value.fullPrice = _parsedDiscountRule.fullPrice
    form.value.reducePrice = _parsedDiscountRule.reducePrice
    form.value.discount = _parsedDiscountRule.discount
    form.value.maxDiscountPrice = _parsedDiscountRule.maxDiscountPrice
  }
  
  // 领取时间限制
  if (form.value.receiveType === 1 && form.value.receiveRangeStartTime && form.value.receiveRangeEndTime) {
    receiveLimitDayTimeModel.value = [ getTimestampByHHmmss(form.value.receiveRangeStartTime), getTimestampByHHmmss(form.value.receiveRangeEndTime) ]
  } 
  if (form.value.receiveType === 2 && form.value.receiveRangeStartTime && form.value.receiveRangeEndTime) {
    receiveWeekDayModel.value = (form.value?.receiveWeekDay ?? '').split(",")
    receiveLimitWeekTimeModel.value = [ getTimestampByHHmmss(form.value.receiveRangeStartTime), getTimestampByHHmmss(form.value.receiveRangeEndTime) ]
  }
  if (form.value.receiveType === 3 && form.value.receiveRangeStartTime && form.value.receiveRangeEndTime) {
    receiveMonthModel.value = (form.value?.receiveMonth ?? '').split(",")
    receiveLimitMonthTimeModel.value = [ getTimestampByHHmmss(form.value.receiveRangeStartTime), getTimestampByHHmmss(form.value.receiveRangeEndTime) ]
  }

  // 使用结束时间
  if (form.value.useType === 0) {
    useFixEndTimeModel.value = form.value.useFixEndTime
  }
}


onMounted(() => {
  if (mode.value === 'edit') {
    echoForm()
  }

  _getMallList();
})
</script>

<style scoped lang="scss">
:deep(.common-form-item) {
  .el-form-item__content {
    flex: unset;
  }

  .el-input {
    width: 300px;
  }

  .el-input.form-input__120 {
    width: 120px;
  }

  .gapped-form-item {
    margin-right: 10px;
  }
}

.business-form-item {
  .goods-select {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 214px;
    height: 32px;
    background: #e6e9f1;
    border-radius: 4px;
    cursor: pointer;
    color: var(--el-color-primary);
    margin-left: 10px;
  }

  .business-row {
    display: flex;
    justify-content: flex-start;
    align-items: center;
  }

  .cate-select {
    margin-left: 10px;
  }
}

.business-form-item__column {
  :deep(.el-form-item__content) {
    display: flex;
    align-items: flex-start;
    flex-direction: column;
  }

  .business-column-item {
    margin-bottom: 10px;
  }
}

.radio-box {
  display: flex;
  
  .radio-item {
    min-width: 100px;
    min-height: 50px;
    box-sizing: border-box;
    position: relative;
    border-radius: 5px;
    cursor: pointer;
    border: solid 1px #dcdfe6;

    .radio-item-checked-cover {
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
      z-index: 1;
      border: solid var(--el-color-primary) 1px;
      border-radius: 5px;
      pointer-events: none;

      .check-icon {
        position: absolute;
        right: 0;
        bottom: 0;
        color: white;
      }
    }

    .radio-item-checked-cover:after {
      content: "";
      width: 0px;
      height: 0px;
      // background: var(--el-color-primary);
      position: absolute;
      right: 0;
      bottom: -28px;
      z-index: -1;
      border-left: solid 20px var(--el-color-primary);
      border-bottom: solid 20px transparent;
      border-right: solid 20px transparent;
      border-top: solid 20px transparent;
      transform-origin: bottom right;
      transform: rotate(45deg);
    }
  }

  .radio-item:not(:last-child) {
    margin-right: 10px;
  }
}

.radio-box__disabled {
  .radio-item {
    cursor: not-allowed;

    .radio-item-checked-cover {
      border: solid transparent 1px;
    }

    .radio-item-checked-cover:after {
      border-left: solid 20px #dcdfe6;
    }
  }
}

.coupon-type-inner {
  width: 120px;
  height: 70px;
  padding: 10px;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;

  .title1 {
    font-size: 16px;
    color: var(--el-color-primary);
    line-height: 1.5;
  }
  .title2 {
    font-size: 12px;
    color: #999;
    line-height: 1.3;
  }
}

.inline-form-input {
  // display: inline-block;
  margin: 0 10px;
}

.discount-rule {
  margin-bottom: 10px;
}

:deep(.column-radio-group) {
  display: flex;
  flex-direction: column;
  align-items: flex-start;

  .el-radio {
    margin-bottom: 10px;
    height: unset;
  }

  .el-radio__label {
    display: inline-flex;
  }

  .radio-inner-item {
    margin-right: 10px;
  }

  .select-width__120 {
    width: 120px;
  }

  .input-width__120 {
    width: 120px;
  }
}

.fixed-bottom {
  padding: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.coupon-warning-notice {
  margin-left: 120px;
  margin-bottom: 18px;
  color: #999;
  font-size: 12px;
}
</style>